package com.hibase.core.mybatis.config;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.core.injector.ISqlInjector;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.hibase.core.mybatis.handler.HibaseMetaObjectHandler;
import com.hibase.core.mybatis.registrar.HibaseSqlInjector;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * mybatis配置
 *
 * @author hufeng
 * @date 2019/03/22
 */
@Configuration
public class MybatisConfig {

    /**
     * 分页插件 (旧版：3.1.1)
     */
//    @Bean
//    public PaginationInterceptor paginationInterceptor() {
//        return new PaginationInterceptor();
//    }

    // 注册乐观锁和分页插件(新版：3.4.0)
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor(){
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor()); // 乐观锁插件
        // DbType：数据库类型(根据类型获取应使用的分页方言)
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL)); // 分页插件
        return interceptor;
    }

    /**
     * 自定义sql
     */
    @Bean
    public ISqlInjector sqlInjector() {
        return new HibaseSqlInjector();
    }

    /**
     * 乐观锁 (旧版：3.1.1)
     * @return
     */
//    @Bean
//    public OptimisticLockerInterceptor optimisticLockerInterceptor() {
//        return new OptimisticLockerInterceptor();
//    }
    @Bean
    public HibaseMetaObjectHandler hibaseMetaObjectHandler(){
        return new HibaseMetaObjectHandler();
    }

    @Bean
    public CustomIdGenerator customIdGenerator(){
        return new CustomIdGenerator();
    }

    /**
     * 打印sql分析器
     *
     * @return
     */
    @Bean
    @ConditionalOnProperty(name = "hibase.mybatis.enablePrintSQL",havingValue = "true",matchIfMissing = true)
    public PrintSQLPerformanceInterceptor printSQLPerformanceInterceptor() {
        PrintSQLPerformanceInterceptor interceptor = new PrintSQLPerformanceInterceptor();
        return interceptor;
    }
}
